package filter;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

import org.hibernate.Session;

import db.DbUtils;

 public class LoginLogoutServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
	 
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		HttpSession session = req.getSession();
		session.invalidate();
		resp.sendRedirect("Home.jsp?page=1");
		return;
	}

	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String action = request.getParameter("action");
		if(action.equalsIgnoreCase("login")) {
			String userName = request.getParameter("username").trim();
			String userPassword = request.getParameter("userpassword");
			Session hbSession = DbUtils.startSession();
			if(DbUtils.isValidUser(hbSession, userName, userPassword)) {
				//�� ��������� �� username � MyAlbum.jsp 
				HttpSession session = request.getSession();
		        session.setAttribute("user", userName);
		        long userId = DbUtils.getUserIdByUserName(hbSession, userName);
		        session.setAttribute("userid", userId);
		        hbSession.close();
				response.sendRedirect("MyAlbum.jsp?root=true");
				return;
			} else {
				hbSession.close();
				response.sendRedirect("Error.jsp?msg=invaliduser");
			}
		} else {
			HttpSession session = request.getSession();
			session.invalidate();
			response.sendRedirect("Home.jsp?page=1");
			return;
		}
	}
}